package com.raytoo.module.sys.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.raytoo.common.constant.factory.ConstantFactory;
import com.raytoo.common.constant.state.MenuStatus;
import com.raytoo.common.constant.tips.Tip;
import com.raytoo.common.controller.BaseController;
import com.raytoo.common.exception.BizExceptionEnum;
import com.raytoo.common.exception.BussinessException;
import com.raytoo.common.node.ZTreeNode;
import com.raytoo.common.persistence.dao.MenuMapper;
import com.raytoo.common.persistence.model.Menu;
import com.raytoo.core.log.LogObjectHolder;
import com.raytoo.core.support.BeanKit;
import com.raytoo.core.util.ToolUtil;
import com.raytoo.module.sys.dao.MenuDao;
import com.raytoo.module.sys.service.IMenuService;
import com.raytoo.module.sys.warpper.MenuWarpper;

/**
 * 菜单服务控制器
 */
@Controller
@RequestMapping("/sys/menu")
public class MenuController extends BaseController {

    private String PREFIX = "/sys/menu/";
    
    @Resource
    MenuMapper menuMapper;

    @Resource
    MenuDao menuDao;

    @Resource
    IMenuService menuService;
    
    /**
     * 跳转到菜单服务首页
     */
    @RequestMapping("")
    public String menu() {
        return PREFIX + "menu";
    }

    /**
     * 跳转到添加菜单服务
     */
    @RequestMapping("/menu_add")
    public String menuAdd() {
        return PREFIX + "menu_add";
    }

    /**
     * 跳转到修改菜单服务
     */
    @RequestMapping("/menu_edit/{id}")
    public String menuEdit(@PathVariable Integer id, Model model) {
    	if(ToolUtil.isEmpty(id)){
    		throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
    	}
    	Menu menu = this.menuMapper.selectById(id);
    	 //获取父级菜单的id
        Menu temp = new Menu();
        temp.setCode(menu.getPcode());
        Menu pMenu = this.menuMapper.selectOne(temp);

        //如果父级是顶级菜单
        if (pMenu == null) {
            menu.setPcode("0");
        } else {
            //设置父级菜单的code为父级菜单的id
            menu.setPcode(String.valueOf(pMenu.getId()));
        }

        Map<String, Object> menuMap = BeanKit.beanToMap(menu);
        menuMap.put("pcodeName", ConstantFactory.me().getMenuNameByCode(temp.getCode()));
        model.addAttribute("menu", menuMap);
        LogObjectHolder.me().set(menu);
        return PREFIX + "menu_edit";
    }
    
    /**
     * 修改菜单服务
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Tip edit(@Valid Menu menu, BindingResult result) {
    	if(result.hasErrors()){
    		throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
    	}
    	
    	//设置父级菜单
    	menuSetPcode(menu);
    	this.menuMapper.updateById(menu);
        return super.SUCCESS_TIP;
    }


    /**
     * 根据请求的父级菜单编号设置pcode和层级
     * @param menu
     */
    private void menuSetPcode(@Valid Menu menu) {
    	String pcode = menu.getPcode();
		if(ToolUtil.isEmpty(pcode) || ToolUtil.equals(pcode, "0")){
			menu.setPcode("0");
			menu.setLevels(1);
		} else {
			int code = Integer.parseInt(pcode);
			Menu pMenu = this.menuMapper.selectById(code);
			Integer pLevels = pMenu.getLevels();
			menu.setPcode(pMenu.getCode());
            menu.setLevels(pLevels + 1);
            menu.setPcodes(pMenu.getPcodes() + "[" + pMenu.getCode() + "],");
		}
		
	}

	/**
     * 获取菜单服务列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String menuName, @RequestParam(required = false) String level) {
    	List<Map<String, Object>> menus = this.menuDao.selectMenus(menuName, level);
        return super.warpObject(new MenuWarpper(menus));
    }

    /**
     * 新增菜单服务
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@Valid Menu menu, BindingResult result) {
    	if(result.hasErrors()){
    		throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
    	}
    	//设置父级菜单编号
        menuSetPcode(menu);

        menu.setStatus(MenuStatus.ENABLE.getCode());
        this.menuMapper.insert(menu);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除菜单服务
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer menuId) {
    	if(ToolUtil.isEmpty(menuId)){
    		throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
    	}
    	//缓存菜单的名称
        LogObjectHolder.me().set(ConstantFactory.me().getMenuName(menuId));

        this.menuService.delMenuContainSubMenus(menuId);
        return SUCCESS_TIP;
    }


    /**
     * 查看菜单
     */
    @RequestMapping(value = "/view/{menuId}")
    @ResponseBody
    public Tip view(@PathVariable Integer menuId) {
        if (ToolUtil.isEmpty(menuId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        this.menuMapper.selectById(menuId);
        return SUCCESS_TIP;
    }
    
    /**
     * 获取菜单列表(首页用)
     */
    @RequestMapping(value = "/menuTreeList")
    @ResponseBody
    public List<ZTreeNode> menuTreeList() {
        List<ZTreeNode> roleTreeList = this.menuDao.menuTreeList();
        return roleTreeList;
    }

    /**
     * 获取菜单列表(选择父级菜单用)
     */
    @RequestMapping(value = "/selectMenuTreeList")
    @ResponseBody
    public List<ZTreeNode> selectMenuTreeList() {
        List<ZTreeNode> roleTreeList = this.menuDao.menuTreeList();
        roleTreeList.add(ZTreeNode.createParent());
        return roleTreeList;
    }
    
    /**
     * 获取角色列表
     */
    @RequestMapping(value = "/menuTreeListByRoleId/{roleId}")
    @ResponseBody
    public List<ZTreeNode> menuTreeListByRoleId(@PathVariable Integer roleId) {
        List<Integer> menuIds = this.menuDao.getMenuIdsByRoleId(roleId);
        if (ToolUtil.isEmpty(menuIds)) {
            List<ZTreeNode> roleTreeList = this.menuDao.menuTreeList();
            return roleTreeList;
        } else {
            List<ZTreeNode> roleTreeListByUserId = this.menuDao.menuTreeListByMenuIds(menuIds);
            return roleTreeListByUserId;
        }
    }
}
